/*
 *  ui_dialog 0.1
 *  独门绝学出品
 *
 *	备份于 2011年  作者  董恒
 *
 *	备份日期:2011-11-03
 **/
 
 /**
 ** var dialog = $.ui_dialog_create();
	dialog._create(conf);
	dialog.openDialog();
 **/
(function($){
    //弹出框默认调用方法
    $.fn.ui_grid = function(gridId){
    	
    };
    
    $.ui_grid_create = function(){
        return new ui_grid_component();
    };
	
	//给每次创建的索引加1
	$.ui_grid_id = Date.parse(new Date());
	
    //内部方法，创建弹出框
    function ui_grid_component(){
		
    	if (typeof ui_grid_component.baseParam == "undefined") {
        
            //初始化单选组件参数为必配置参数
            ui_grid_component.baseParam = {
                
            };
        };
    
        return {
            //所有属性方法配置详细列表
            setting: {
				gridId:'',
                callback: {
                    beforeInsertRow: function(){
                    	
                    },
					beforeDelRow:function(){
						
					},
					beforeHoverRow:function(){
						
					},
					beforeEditRow:function(){
						
					},
					beforeSelectedEditRow:function(){
						
					},
					beforeSelectedDelRow:function(){
						
					},
					beforeViewRow:function(){
						
					},
					
					onDblClick:function(){
					
					},
					onUpdateRow:function(){
						
					},
					onDelRow:function(){
						
					},
					onSelectedDelRow:function(){
						
					},
					onJumpPage:function(){
						
					},
					onChangePageInfo:function(pageInfo){
							
					}
                },
				data:{
					headerData:[{
						title:'留言用户昵称或账户ID',
						sortName:'id',
						width:'200px'	
					},{
						title:'留言内容',
						sortName:'content',
						width:'200px'	
					},{
						title:'用户邮件',
						sortName:'mail',
						width:''	
					},{
						title:'联系电话',
						sortName:'tel',
						width:''	
					},{
						title:'留言时间',
						sortName:'datetime',
						width:''	
					},{
						title:'功能操作',
						sortName:'gridControl',
						width:'600px'	
					}],
					key:{
						id:'id'	
					}
				},
				view:{
					showSort:null,
					showCheckbox:true,
					btn:[/*{
							view:{
								showViewTxt:'测试'
							},
							css:{
								'color':'blue'
							},
							callback:{
								onClick:function(gridNodes){
									alert(gridNodes.id);
								}
							}
						}*/]
				}
            },
            /**
             * 功能：创建一个新的弹出框
             * @参数 {Object} gridData 菜单框对象
             */
            init: function(setting,gridData,gridPageInfo){
            	var _this = this;
                var gridId = 'grid'+$.ui_grid_id++;
                //取得弹出框个性化配置
                var opts = $.extend({}, setting);
				
				//将弹出框的默认配置和个性配置合并
				if (opts && opts.callback) {
                    this.setting.callback = $.extend({}, this.setting.callback, opts.callback);
                    delete opts.callback;
                }
				if (opts && opts.data) {
                    this.setting.data = $.extend({}, this.setting.data, opts.data);
                    delete opts.data;
                }
				if (opts && opts.view) {
                    $.extend(true, this.setting.view, opts.view);
                    delete opts.view;
                }
				if (opts && opts.gridId) {
                    this.setting.gridId = opts.gridId;
                    delete opts.gridId;
                }
				
				//整理生成的ID
				if(this.setting.gridId)gridId = this.setting.gridId;
				else{
					this.setting.gridId = gridId;
					this.gridIdAuto = true;	
				}
				
				var gridNodes = this.dataDealNodes(gridData);
				this.gridNodes = gridNodes;
				
				this.makeGrid(this.gridNodes);
				
				this.pageInfo = this.dataDealPageInfo(gridPageInfo);
				//第一次监听翻译情况
				this.setting.callback.onChangePageInfo(this.pageInfo);
            },
			/**
        	 * 所有数据进行处理
			 * return gridNodes
        	 */
			dataDealNodes:function(gridData){
				var gridNodes = new Array(),
				setting = this.setting;
				
				if(gridData){
					for(var i=0;i<gridData.length;i++){
						gridNodes.push(this.dataDealNode(gridData[i]));
					}
				}else{
					alert('请传入有效的数据再进行操作！');	
				}
				
				return gridNodes;
			}, 
			/**
			** 单个数据进行处理
			**/
			dataDealNode:function(gridDataItem){
				var gridNode = {};
				
				var setting = this.setting;
				//处理ID问题
				eval('var gridNodeId = gridDataItem.'+setting.data.key.id);
				gridNode.id = gridNodeId;
				//把参数装入该对象中
				for(var param in gridDataItem){
					if(param!='id')
						eval('gridNode.'+param+'=gridDataItem[param];');
				}
				
				gridNode.isChecked = false;
				return gridNode;
			},
			/**
			**
			**/
			dataDealPageInfo:function(gridPageInfo){
				if(gridPageInfo){
					//当前页不能大于总页数
					if(gridPageInfo.currentPage>gridPageInfo.countPage)
						gridPageInfo.currentPage = gridPageInfo.countPage;
					//当前页不能小于1
					if(gridPageInfo.currentPage<1)
						gridPageInfo.currentPage = 1;
						
					//是否有上一页
					if(gridPageInfo.currentPage<=1)
						gridPageInfo.isPrePage = false;
					else
						gridPageInfo.isPrePage = true;
						
					//是否有下一页
					if(gridPageInfo.currentPage>=gridPageInfo.countPage)
						gridPageInfo.isNextPage = false;
					else
						gridPageInfo.isNextPage = true;
				}
				return gridPageInfo;
			},
        	/**
        	 * 生成表格方法
        	 */
			makeGrid:function(gridNodes){
				var setting = this.setting;
				var uiTable = $('<table cellspacing="0" cellpadding="0"></table>').addClass('tb-table');
				if(this.gridIdAuto){
					$('#'+setting.gridId).remove();
					uiTable.appendTo(window.document.body);
					uiTable.attr('id',setting.gridId);
				}
				else{
					if(typeof setting.gridId == 'object'){
					    setting.gridId.empty();
					    uiTable.appendTo(setting.gridId);
					}
					else{
					   $('#'+setting.gridId).empty();
					   uiTable.appendTo('#'+setting.gridId);
				    }
				}
					
				this.makeGridHeader(gridNodes,uiTable);
				
				this.makeGridCore(gridNodes,uiTable);
			},
			/**
			** 生成表格头部
			**/
			makeGridHeader:function(gridNodes,uiTable){
				var setting = this.setting;
				var headerTr = $('<tr></tr>').addClass('tb-table-title').appendTo(uiTable);
				if(setting.view.showCheckbox){
					var headerTdCheckbox = $('<td></td>').addClass('checkbox').appendTo(headerTr);
					var headerTdInput = (this.totalCheckbox = $('<input type="checkbox">')).appendTo(headerTdCheckbox);
					//总状态事件监控
					this.selectedTotalStatu(this.totalCheckbox);
				}
				
				for(var i=0;i<setting.data.headerData.length;i++){
					var headerDataItem = setting.data.headerData[i];
					var headerTd = $('<td></td>').width(headerDataItem.width?headerDataItem.width:'').attr('sortName',headerDataItem.sortName).appendTo(headerTr);
					var headerSpan = $('<span></span>').text(headerDataItem.title).appendTo(headerTd);
				}
			},
			/**
			** 生成表格核心
			**/
			makeGridCore:function(gridNodes,uiTable){
				var setting = this.setting,
				_this = this;
				
				for(var i=0;i<gridNodes.length;i++){
					var rowTr = (gridNodes[i].rowTr = $('<tr></tr>')).hover(function(){
						$(this).addClass('tr-mouseover');	
					},function(){
						$(this).removeClass('tr-mouseover');		
					}).appendTo(uiTable);
					if(setting.view.showCheckbox){
					var rowTdCheckbox = $('<td></td>').appendTo(rowTr);
						var rowTdInput = (gridNodes[i].rowTdCheckbox = $('<input type="checkbox">')).appendTo(rowTdCheckbox);
						this.selectedRow(gridNodes[i]);
					}
					
					for(var j=0;j<setting.data.headerData.length;j++){
						var headerDataItem = setting.data.headerData[j];
						var headerTd = null;
						if(headerDataItem.sortName != 'gridControl'){
						    var gridNodeData = eval('gridNodes[i].'+headerDataItem.sortName);
						    if(headerDataItem.callback){
						        gridNodeData = headerDataItem.callback(gridNodeData);
						    }
							headerTd = $('<td></td>').html(gridNodeData || ' ').appendTo(rowTr);	
						}else{
							headerTd = $('<td></td>').appendTo(rowTr);	
							//查看是否有自定义
							if(setting.view.btn && setting.view.btn.length>0){
								gridNodes[i].customNode = [];
								for(var m in setting.view.btn){
									gridNodes[i].customNode.push($('<a></a>').css(setting.view.btn[m].css || {}).attr('nodeId',gridNodes[i].id).addClass('op').click((function(n,p){
										return function(){
											setting.view.btn[n].callback.onClick(_this.findGridNodeById(p));
										};
									})(m,gridNodes[i].id)).text(setting.view.btn[m].view.showViewTxt).appendTo(headerTd));
								};
							};
						}
					}
				}	
			},
			//总状态事件监控
			selectedTotalStatu:function(totalCheckbox){
				var _this = this;
				totalCheckbox.click(function(){
					if($(this).attr('checked')){
						for(var i=0;i<_this.gridNodes.length;i++){
							_this.gridNodes[i].rowTdCheckbox.attr('checked',true);	
							_this.gridNodes[i].isChecked = true;
						}	
					}else{
						for(var i=0;i<_this.gridNodes.length;i++){
							_this.gridNodes[i].rowTdCheckbox.attr('checked',false);	
							_this.gridNodes[i].isChecked = false;
						}		
					}
				});
			},
			/**
			** 根据ID找寻值
			**/
			findGridNodeById:function(nodeId){
				for(var i=0;i<this.gridNodes.length;i++){
					if(this.gridNodes[i].id == nodeId)	
						return this.gridNodes[i];
				}	
			},
			/**
			** 表格多选事件处理
			**/
			selectedRow:function(gridNode){
				var _this = this;
				gridNode.rowTdCheckbox.click(function(){
					if($(this).attr('checked'))	
						gridNode.isChecked = true;
					else
						gridNode.isChecked = false;
						
					//重新计算总选择状态
					_this.calculateTotalSelectedRow();
				});
			},
			/**
			** 计算总选中状态
			**/
			calculateTotalSelectedRow:function(){
				for(var i=0;i<this.gridNodes.length;i++){
					if(this.gridNodes[i].isChecked == false){
						this.totalCheckbox.attr('checked',false);
						return false;
					}
				}
				this.totalCheckbox.attr('checked',true);
			},
			/**
			** 更新所有数据
			**/
			dataUpdateAll:function(gridData,pageInfo){
				var gridNodes = this.dataDealNodes(gridData);
				this.gridNodes = gridNodes;
				
				this.makeGrid(this.gridNodes);
				
				this.pageInfo = this.dataDealPageInfo(pageInfo);
				//再次监听翻译情况
				this.setting.callback.onChangePageInfo(this.pageInfo);
			},
			selectInsertRow:function(){
				this.beforeInsertRow();
			},
			/**
			** 插入一条数据之前的操作
			**/
			beforeInsertRow: function(){
            	var setting = this.setting;
				setting.callback.beforeInsertRow();   	
			},
			/**
			** 删除一条数据之前的操作
			**/
			beforeDelRow:function(nodeId){
				var setting = this.setting;
				var gridNode = this.findGridNodeById(nodeId);
				setting.callback.beforeDelRow(gridNode);
			},
			beforeViewRow:function(nodeId){
				var setting = this.setting;
				var gridNode = this.findGridNodeById(nodeId);
				setting.callback.beforeViewRow(gridNode);
			},
			/**
			** 指向一条数据的操作
			**/
			beforeHoverRow:function(){
				var setting = this.setting;
				var gridNode = this.findGridNodeById(nodeId);
				setting.callback.beforeHoverRow(gridNode);
			},
			/**
			** 编辑一条数据的操作
			**/
			beforeEditRow:function(nodeId){
				var setting = this.setting;
				var gridNode = this.findGridNodeById(nodeId);
				setting.callback.beforeEditRow(gridNode);
			},
			/**
			** 编辑一条选中记录操作
			**/
			selectedEditRow:function(){
				this.beforeSelectedEditRow();
			},
			/**
			** 编辑一条选中的数据之前的操作
			**/
			beforeSelectedEditRow:function(){
				var setting = this.setting;
				var selectedNodes = new Array();
				//找出当前选中的节点集合
				for(var i=0;i<this.gridNodes.length;i++){
					if(this.gridNodes[i].isChecked){
						selectedNodes.push(this.gridNodes[i]);
					}
				}
				
				//如果记录超过2条则无法编辑该数据
				if(selectedNodes && selectedNodes.length>1){
					alert('编辑的记录不能超过2条!');
					return false;
				}
				else if(selectedNodes && selectedNodes.length<=0){
					alert('必须选择一条记录才能编辑!');	
					return false;
				}
					
				setting.callback.beforeSelectedEditRow();
			},
			/**
			** 删除选中的所有记录
			**/
			selectedDelRow:function(){
				this.beforeSelectedDelRow();
			},
			/**
			** 删除一条选中的数据之前的操作
			**/
			beforeSelectedDelRow:function(){
				var setting = this.setting;
				var selectedNodes = new Array();
				//找出当前选中的节点集合
				for(var i=0;i<this.gridNodes.length;i++){
					if(this.gridNodes[i].isChecked){
						selectedNodes.push(this.gridNodes[i]);
					}
				}
				
				if(selectedNodes && selectedNodes.length<=0)
					alert('请至少选择一条进行记录删除！');
				else
					setting.callback.beforeSelectedDelRow(selectedNodes);
			},
			/**
			** 查看选中的所有记录
			**/
			selectedViewRow:function(){
				return this.beforeSelectedViewRow();
			},
			/**
			** 查看一条选中的数据之前的操作
			**/
			beforeSelectedViewRow:function(){
				var setting = this.setting;
				var selectedNodes = new Array();
				//找出当前选中的节点集合
				for(var i=0;i<this.gridNodes.length;i++){
					if(this.gridNodes[i].isChecked){
						selectedNodes.push(this.gridNodes[i]);
					}
				}
			 return selectedNodes;
			}
		};
    }
})(jQuery);